package com.jiawa.train.gateway.util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final Logger LOG = LoggerFactory.getLogger(JwtUtil.class);

    private static final String JWT_SECRET = "Jiawa12306";

    public static String createToken(Long id, String mobile) {

        DateTime now = DateTime.now();
        DateTime expireTime = now.offsetNew(DateField.HOUR, 24);
        Map<String, Object> payload = new HashMap<>();

        payload.put("id", id);
        payload.put("mobile", mobile);
        // 签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        // 过期时间
        payload.put(JWTPayload.EXPIRES_AT, expireTime);
        // 生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);

        String token = JWTUtil.createToken(payload, JWT_SECRET.getBytes());

        LOG.info("生成JWT-Token: {}", token);
        return token;
    }


    public static boolean validate(String token) {
        try {
            JWT jwt = JWTUtil.parseToken(token).setKey(JWT_SECRET.getBytes());
            boolean validate = jwt.validate(0);
            LOG.info("JWT-Token验证结果: {}", validate);
            return validate;
        } catch (Exception e) {
            LOG.error("JWT-Token验证失败: {}", e);
            return false;
        }
    }

    public static JSONObject getJSONObject(String token) {
        JWT jwt = JWTUtil.parseToken(token).setKey(JWT_SECRET.getBytes());
        JSONObject payloads = jwt.getPayloads();
        payloads.remove(JWTPayload.ISSUED_AT);
        payloads.remove(JWTPayload.EXPIRES_AT);
        payloads.remove(JWTPayload.NOT_BEFORE);
        LOG.info("JWT-Token payloads: {}", payloads);
        return payloads;
    }

    public static void main(String[] args) {
        String token = createToken(1L, "13800000002");
        validate(token);
        getJSONObject(token);
    }

}
